package com.nineclock.system.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired(required = false)
    private SysUserMapper sysUserMapper;

    @Autowired
    private SmsService smsService;
    
    @Override
    public SysUserDTO queryUser(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile, username);
        wrapper.eq(SysUser::getStatus, 1);

        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser != null) {
            return BeanHelper.copyProperties(sysUser, SysUserDTO.class);
        }
        return null;
    }

    @Override
    public void register(SysRegisterDTO sysRegisterDTO) {
        if (sysRegisterDTO==null|| StringUtils.isEmpty(sysRegisterDTO.getCheckcode())||StringUtils.isEmpty(sysRegisterDTO.getMobile())||StringUtils.isEmpty(sysRegisterDTO.getPassword())){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Boolean verifyResult = smsService.verifySmsCode(sysRegisterDTO.getMobile(), sysRegisterDTO.getCheckcode(), SMSConstant.SMS_TYPE_REGISTER);
        if (!verifyResult){
            throw new NcException(ResponseEnum.INVALID_VERIFY_CODE);
        }
        SysUser sysUser = new SysUser();
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysRegisterDTO.getPassword()));
        sysUser.setMobile(sysRegisterDTO.getMobile());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setStatus((short)1);
        sysUserMapper.insert(sysUser);
    }
}